package com.whj.controller;

import com.whj.entity.Loan;
import com.whj.service.LoanService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@Controller
@RequestMapping("/loan")
public class LoanController {
    @Autowired
    private LoanService loanService;
    @RequestMapping("/toLoan")
    public String toLoan(){
        return "loan";
    }
    @RequestMapping("/showLoan")
    public String showLoan(Model model){
        List<Loan> loans = loanService.selectList();
        model.addAttribute("loans",loans);
        return "showloan";
    }
    @PostMapping("/addLoan")
    public String addLoan(Loan loan, @RequestParam("image") MultipartFile image,  HttpServletRequest request,Model  model){
            try {
                // 定义文件存储路径
                String uploadDir = "C:/loan_uploads/";
                File uploadPath = new File(uploadDir);
                if (!uploadPath.exists()) {
                    uploadPath.mkdirs();
                }
                // 保存文件
                String fileName = System.currentTimeMillis() + "_" + image.getOriginalFilename();
                File dest = new File(uploadPath, fileName);
                image.transferTo(dest);
                // 创建 Loan 对象并保存图片路径
                loan.setImg("/uploads/" + fileName); // 保存相对路径到数据库
                // 保存 loan 对象到数据库
                // loanService.save(loan);

            } catch (IOException e) {
                e.printStackTrace();
                // 处理异常
            }
        loanService.addLoan(loan);
            model.addAttribute("msg", "申请成功！");
            return "loan";
    }
    @RequestMapping("/updateStatus")
    public String updateStatus(Integer id, Integer status){
        loanService.update(id,status);
        return "redirect:/loan/showLoan";
    }
    @RequestMapping("/selectById")
    public String selectById(Integer userId, Model model){
        System.out.println("id:"+userId);
        List<Loan> loans = loanService.selectById(userId);
        model.addAttribute("loans",loans);
        List<Loan> wsh = loanService.selectBysta(0);
        List<Loan> ysh = loanService.selectBysta(1);
        List<Loan> yjj = loanService.selectBysta(2);
        model.addAttribute("wsh",wsh);
        model.addAttribute("ysh",ysh);
        model.addAttribute("yjj",yjj);
        return "loanlist";
    }
}
